<?php
class catalog_category {

	private static $_allCategory = null;
	/**
	 * 這里可以用緩存
	 * @see catalog_category_concept::fetchAll()
	 */
	public static function allCategory() {
		if(self::$_allCategory === null) {
			$_allCategories = array();
			$concept = new catalog_category_concept();
			foreach($concept->fetchAll(array(), array('display_order ASC')) AS $row) {
				$_allCategories[] = $row;
			}
			self::$_allCategory = $_allCategories;
		}
		return self::$_allCategory;
	}
	
	public static $_path = array();
	/**
	 * 分類麵包序
	 * 如: c1 > c2 > c3
	 */
	public static function categoryPath($cid) {
		foreach(self::allCategory() AS $row) {
			if($row->getId() == $cid) {
				self::$_path[] = $row;
				if($row->getParentId() > 0) {
					self::categoryPath($row->getParentId());
				}
				break;
			}
		}
		return self::$_path;
	}
	
	public static function allCategoryToTreeAsArray($pid = 0) {		
		$tree = array();
		foreach(self::allCategory() AS $key => $row) {
			if($row->getParentId() == $pid) {
				$tree[$row->getId()] = array(
						'id' => $row->getId(),
						'parent' => $row->getParentId(),
						'name' => $row->getName(),
						'ename' => $row->getEname(),
						'is_active' => $row->getIsActive(),
						'children' => self::allCategoryToTreeAsArray($row->getId())
				);
			}
		}
		return $tree;
	}
	
}